﻿using Microsoft.Extensions.DependencyInjection;
using ZeroSum.DependencyInjection.Attributes;
using ZeroSum.Extend.Mapper.Extensions;
using ZeroSum.Models;
using ZeroSumZSA.Application.ApplicationServices.Roles.Dto.In;
using ZeroSumZSA.Application.ApplicationServices.Roles.Dto.Out;
using ZeroSumZSA.Application.ApplicationServices.Roles.Dto.Query;
using ZeroSumZSA.Core.Aggregates.RoleAggregate;
using ZeroSumZSA.Core.DomainServices.Roles;

namespace ZeroSumZSA.Application.ApplicationServices.Roles;

[Register(ServiceLifetime.Scoped)]
public class RoleApplicationService : IRoleApplicationService
{
    private readonly IRoleDomainService _roleDomainService;

    public RoleApplicationService(IRoleDomainService roleDomainService)
    {
        _roleDomainService = roleDomainService;
    }

    public async Task<PagedResponseModel<PageRoleDto>> Page(PageRoleQuery query)
    {
        var roles = await _roleDomainService.Query(query.Keyword, query.PageNumber, query.PageSize);
        var count = await _roleDomainService.Count(query.Keyword);
        var list = roles.MapTo<List<PageRoleDto>>();
        return new PagedResponseModel<PageRoleDto>(query.PageNumber, query.PageSize, count, list);
    }

    public async Task AddAsync(AddRoleDto dto)
    {
        var entity = dto.MapTo<Role>();
        await _roleDomainService.AddAsync(entity);
    }

    public async Task DeleteAsync(DeleteRoleDto dto)
    {
        await _roleDomainService.DeleteAsync(dto.Id);
    }

    public async Task UpdateAsync(EditRoleDto dto)
    {
        await _roleDomainService.CheckRoleUpdate(dto.Name, dto.Code, dto.Id);
        var role = await _roleDomainService.GetByIdAsync(dto.Id);
        var entity = dto.MapTo(role);
        await _roleDomainService.UpdateAsync(entity);
    }

    public async Task<DetailRoleDto> Detail(DetailRoleQuery query)
    {
        var role = await _roleDomainService.GetByIdAsync(query.Id);
        return role.MapTo<DetailRoleDto>();
    }
}